package com.ad.backstage.controller;

import com.ad.backstage.common.constant.Const;
import com.ad.backstage.common.constant.WxConst;
import com.ad.backstage.common.utils.FastJsonUtil;
import com.ad.backstage.common.utils.RestTemplateUtil;
import com.ad.backstage.model.Merchant;
import com.ad.backstage.model.MerchantPojo;
import com.ad.backstage.model.WxUser;
import com.ad.backstage.service.IMerchantSystemService;
import com.ad.payload.enums.ResultCode;
import com.ad.payload.model.ResultBean;
import com.ad.payload.util.JwtUtil;
import com.ad.payload.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:dxgong
 * @日期 2020/3/4 15:43
 * @注释
 */
@RequestMapping("/WeChatLoginSystemApi")
@RestController
@Slf4j
public class LoginSystemController {

    @Autowired
    private IMerchantSystemService iMerchantSystemService;

    @Autowired
    private JwtUtil jwtUtil;


    /**
     * 商家端小程序登录
     */
    @RequestMapping("/back/noAuth/login")
    public ResultBean<MerchantPojo> login(@RequestParam(value = "code") String code) {
        log.info("code: " + code);
        if (StringUtil.isBlank(code)) {
            return ResultBean.build(ResultCode.FAILED.getCode(), "登录code不能为空!");
        }
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        String url = WxConst.JS_CODE_2_SESSION + "appid=" + WxConst.MERCHANT_APP_ID + "&secret="
                + WxConst.MERCHANT_APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        String s = RestTemplateUtil.sendPostRequest(url, params, Const.GET_CODE);
        JSONObject jsonObjectToJsonStr = FastJsonUtil.getJsonObjectToJsonStr(s);
        String openId = jsonObjectToJsonStr.getString("openid");
        String sessionKey = jsonObjectToJsonStr.getString("session_key");
        String unionId = jsonObjectToJsonStr.getString("unionid");
        // 同步根据openid添加微信用户
        log.info("===== openId ===== : " + openId);
        log.info("===== session_key ===== : " + sessionKey);
        log.info("===== unionId ===== : " + unionId);
        // 根据unionId保存openId
        WxUser wxUser = new WxUser();
        wxUser.setUnionId(unionId);
        wxUser.setMerchantOpenId(openId);
        this.iMerchantSystemService.updateWxUserByUnionId(wxUser);


        // 根据union查询
        ResultBean<WxUser> wxUserResultBean = this.iMerchantSystemService.queryWxUserByUnionId(unionId);
        if (wxUserResultBean.getCode() != ResultCode.SUCCESS.getCode()) {
            return ResultBean.build(ResultCode.FAILED.getCode(), wxUserResultBean.getMsg());
        }
        WxUser data = wxUserResultBean.getData();

        String uuid = data.getUuid();
        ResultBean<Merchant> merchantResultBean = this.iMerchantSystemService.queryMerchantByUuid(uuid);
        if (merchantResultBean.getCode() != ResultCode.SUCCESS.getCode()) {
            log.info("=====当前opendId["+openId+"]未注册成商家, 请先注册成商家====");
            return ResultBean.build(ResultCode.FAILED.getCode(), "请先关注公众号注册成商家!");
            // return ResultBean.build(Const.FAIL_CODE, "该用户尚未注册成商家");
        }
        Merchant merchant = merchantResultBean.getData();
        MerchantPojo merchantPojo = new MerchantPojo();
        merchantPojo.setUserType(data.getUserType());
        if(merchant != null){
            merchantPojo.setMerchantName(merchant.getName());
            merchantPojo.setMerchantId(merchant.getId());
            merchantPojo.setImg(merchant.getCoverIcon());
            merchantPojo.setActive(merchant.getActive());
            merchantPojo.setExamineStatus(merchant.getExamineStatus());
            merchantPojo.setExamineTimes(merchant.getExamineTimes());
        } else {
            merchantPojo.setMerchantName("请完善商家信息");
            merchantPojo.setImg("https://img.yzcdn.cn/vant/cat.jpeg");
        }
        merchantPojo.setUuid(uuid);


        Map<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("id", data.getId());
        map.put("weChatName", data.getWechatName());
        String jwt = jwtUtil.createJWT(map);
        merchantPojo.setJwtToken(jwt);

        return ResultBean.success(merchantPojo);
    }
}
